/*
============================================================================
 Name        : $(Basename)Session.cpp
 Author      : $(Author)
 Version     :
 Copyright   : $(Copyright)
 Description : $(Basename)Server session.
============================================================================
*/

#include "$(Basename)Server.h"
#include "$(Basename)Session.h"

C$(Basename)ServerSession* C$(Basename)ServerSession::NewL(C$(Basename)Server& aServer)
	{
	C$(Basename)ServerSession* self = C$(Basename)ServerSession::NewLC(aServer);
	CleanupStack::Pop(self);
	return self;
	}

C$(Basename)ServerSession* C$(Basename)ServerSession::NewLC(C$(Basename)Server& aServer)
	{
	C$(Basename)ServerSession* self = new(ELeave) C$(Basename)ServerSession(aServer);
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

C$(Basename)ServerSession::C$(Basename)ServerSession(C$(Basename)Server& aServer)
: iServer(aServer)
	{
	}

void C$(Basename)ServerSession::ConstructL()
	{
	iServer.IncrementSessions();
	}

C$(Basename)ServerSession::~C$(Basename)ServerSession()
	{
	iServer.DecrementSessions();
	}

void C$(Basename)ServerSession::ServiceL(const RMessage2& aMessage)
	{
	switch (aMessage.Function())
		{
		case E$(Basename)ServRequestTime:
			RequestTimeL(aMessage);
			break;
		case E$(Basename)ServCancelRequestTime:
			if(iWaitingForTick)
				{
				iMessage.Complete(KErrCancel);
				iWaitingForTick = EFalse;
				}
			aMessage.Complete(KErrNone);
			break;
		default:
			PanicClient(aMessage, EBadRequest);
		}
	}

void C$(Basename)ServerSession::RequestTimeL(const RMessage2& aMessage)
	{
	if(iWaitingForTick)
		{
		PanicClient(aMessage, EReqAlreadyPending);
		}
	else
		{
		iMessage = aMessage;

		// Start the work performed by the server
		// (just a wait for new second in this example)
		iServer.WaitForTickL();
		iWaitingForTick = ETrue;
		}
	}

void C$(Basename)ServerSession::SendTimeToClient()
	{
	if(iWaitingForTick)
		{
		iWaitingForTick = EFalse;

		TTime time;
		time.HomeTime();

		// Create a descriptor which points to the 'time' structure
		TPtr8 ptr(reinterpret_cast<TUint8*>(&time), sizeof(time), sizeof(time));
		TRAPD(leave, iMessage.WriteL(0, ptr));
		if(leave)
			{
			PanicClient(iMessage, EBadDescriptor);
			}

		iMessage.Complete(E$(Basename)ServRequestTimeComplete);
		}
	}

void C$(Basename)ServerSession::PanicClient(const RMessagePtr2& aMessage, TInt aPanic) const
	{
	aMessage.Panic(K$(Basename)Server, aPanic);
	}
